(function() {
	var app = angular.module('MicroServicesManageApp', [ 'ui.bootstrap' ]);
	app
			.controller(
					'MicroServicesManageController',
					function($http,$scope, $log, $uibModal) {
						var basePath = $scope.getAppBasePath();
						$scope.insertComponent = {};
						$scope.deleteComponent = {};
						var controller = this;
						controller.parameter = {};
						controller.queryParameter = "";
						this.warningConfigList = [];
						this.indexList = [];
//						$scope.processUrl="http://10.7.83.67:8880";
						this.queryCondition = {	
							"miroservice" : "",
							"page" : 1,
							"pageSize" : 8,
						};
						this.paginationInfo = {
							"maxSize" : 8,
							"totalPages" : 0,
							"totalElements" : 0
						};

						$scope.clickEvent = function() {
							controller.queryCondition.page = controller.queryCondition.forwordPage;
							loadData();
						}

						// 跳转页数，回车事件
						$scope.enterEvent = function(e) {
							var keycode = window.event ? e.keyCode : e.which;
							if (keycode == 13) {
								$scope.clickEvent();
							}
						}

						this.pageChanged = function() {
							loadData();
						}
						// 完成全选全部选事件
						$("#check_all").click(
								function() {
									$(".check_item").prop("checked",
											$(this).prop("checked"));
								});
						// 选中单个元素，如果单个元素选择满了，那么第一个主元素也被选中
						$(document)
								.on(
										"click",
										".check_item",
										function() {
											if ($(".check_item:checked").length == $(".check_item").length) {
												$("#check_all").prop("checked",
														true);
											}
											if ($(".check_item:checked").length == 0) {
												$("#check_all").prop("checked",
														false);
											}
										});
						
				
						
						
						// 新增配置
						this.insertConfig = function() {
							
							$scope.insertComponent = {};
							var modalInstanceAdd = $uibModal
									.open({
										backdrop : 'static',
										keyboard : false,
										scope : $scope,
										// animation :
										// $scope.animationsEnabled,// 打开时的动画开关
										templateUrl : 'js/controller/configuration.management/insertMicroService.html',// 模态框的页面内容,这里的url是可以自己定义的,也就意味着什么都可以写
										controller : 'insertMicroServiceController',// 这是模态框的控制器,是用来控制模态框的
										ariaLabelledBy : 'modal-title',
										ariaDescribedBy : 'modal-body',
									// size : "lg",// 模态框的大小尺寸
									});
							
							modalInstanceAdd.opened.then(function(){//模态窗口打开之后执行的函数  
								//加载ip树
								getTreeData(2,[]);
								
							}); 

							modalInstanceAdd.result.then(function(result) {
								loadData();
							});
						}
						// 编辑配置
						this.updateConfig = function() {
							var miroservice = controller.queryCondition.miroservice;
							var page = controller.queryCondition.page;
							var pageSize = controller.queryCondition.pageSize;
							var conditons =  new Array();
							var ids = "";
							var id = "";  
	                        var hostid="";
	                        var port="";
	                        var podName1="";
	                        var podName2="";
							$.each($(".check_item:checked"), function() {
								
								id = $(this).parents("tr").find("td:eq(1)").text();
								hostid = $(this).parents("tr").find("td:eq(2)").text();
								conditons.push(id);
								
							})
							if(conditons == ""){
								alert("请勾选需要编辑的配置");
								return;
							}else if(conditons.length > 1){
								alert("只能选中一个进行配置");
								return;
							}else{
								 
								$scope.editdata = {};
								var modalInstanceAdd = $uibModal
										.open({
											backdrop : 'static',
											keyboard : false,
											scope : $scope,
											// animation :
											// $scope.animationsEnabled,// 打开时的动画开关
											templateUrl : 'js/controller/configuration.management/updateMicroService.html',// 模态框的页面内容,这里的url是可以自己定义的,也就意味着什么都可以写
											controller : 'updateMicroServiceController',// 这是模态框的控制器,是用来控制模态框的
											ariaLabelledBy : 'modal-title',
											ariaDescribedBy : 'modal-body',
										// size : "lg",// 模态框的大小尺寸
										});
								modalInstanceAdd.opened.then(function(){//模态窗口打开之后执行的函数  
									
									 $.ajax({
										 type : "get",
										 dataType : "json",
										 url :basePath+ "/data/selectMiroService",
										 data:{
											 "page":page,
											 "size":pageSize,
											 "miroservice":miroservice
										 },
										 success : function(res) {
											 var resultJson = angular
												.fromJson(res);
											 console.log(resultJson.data);
										 console.log(id);	
										 for(var i=0;i<resultJson.data.length;i++){
											 if(id==resultJson.data[i].id){
												 $scope.id=resultJson.data[i].id;
												 $scope.miroservice=resultJson.data[i].miroservice;
												 $scope.namespace=resultJson.data[i].namespace;
												 $scope.containerName=resultJson.data[i].containerName;
												 $scope.service=resultJson.data[i].service;
												 $scope.port=resultJson.data[i].port;
												 $scope.hostid=resultJson.data[i].hostid;
												 $scope.ip=resultJson.data[i].ip;
												 $scope.podName=resultJson.data[i].podName;
											 }
										 }
										 //手动刷新
										 	$scope.$apply();  
										 },errro:function(){
											 console.log("请求错误！")
										 }
										 });
//									//加载ip树
//									getTreeData(1,data);
					          	});  
								modalInstanceAdd.result.then(function(result) {
									loadData();
								});
			
							}
							
						}
						//删除配置
						this.deleteConfig = function() {
							var id="";
							var hostid="";
							var emp=[];
							var empObjList=[];
							var potLength=[];
							$.each($(".check_item:checked"), function() {
								id = $(this).parents("tr").find("td:eq(1)").text();
								miroservice = $(this).parents("tr").find("td:eq(2)").text();
								namespace = $(this).parents("tr").find("td:eq(3)").text();
								containerName = $(this).parents("tr").find("td:eq(4)").text();
								podName = $(this).parents("tr").find("td:eq(5)").text();
								service = $(this).parents("tr").find("td:eq(6)").text();
								hostid = $(this).parents("tr").find("td:eq(7)").text();
								port = $(this).parents("tr").find("td:eq(8)").text();
								
									 emp[0]={
											 	"id":id,
												"miroservice":miroservice,
												"namespace":namespace,
												"containerName":containerName,
												"service":service,
												"hostid":hostid,
												"port":port,
												"podName":podName
										};
									 empObjList.push(emp[0]);
								
								
							})
							 console.log(empObjList);
							// 如果没有选中的话
							if (id == "") {
								alert("请勾选需要删除的配置");
								return;
							} else {
							
								if (confirm("确认删除该的配置吗?")) {
									// 保存后台调用
									$.ajax({
												type : "POST",
												url : basePath+ "/data/deleteMiroService",
												dataType : "json",
												contentType : 'application/json;charset=utf-8',//指定为json类型 
												data:JSON.stringify(empObjList),
												success : function(data) {
													alert("删除成功");
													loadData();
												}
											});

								}
							}
						}
						
						
						// 搜索事件
						this.search = function() {
							loadData();
						}

						// 重置事件
						this.reset = function() {
							this.queryCondition = {
									"miroservice":"",
									"page" : 1,
									"pageSize" :8,
								};
						}
						
						// 程序初期化
						this.init = function() {
							loadData();
							
						}
						this.init();

						// 加载数据
						function loadData() {
							if ($(".check_item:checked").length == 0) {
								$("#check_all").prop("checked", false);
							}
							
							// 参数获取
							var miroservice= controller.queryCondition.miroservice;
							var page = controller.queryCondition.page;
							var pageSize = controller.queryCondition.pageSize;
//							console.log(ip);
							// 后台调用
							 $.ajax({
							 type : "post",
							 dataType : "json",
							 url :basePath+ "/data/selectMiroService",
							 data:{
								 "page":page,
								 "size":pageSize,
								 "miroservice":miroservice
							 },
							 success : function(res) {
								 var resultJson = angular
									.fromJson(res);
							console.log(resultJson);
//							var emp={
//									"id":"",
//									"miroservice":"",
//									"namespace":"",
//									"containerName":"",
//									"podName1":"",
//								    "podName2":"",
//									"service":"",
//									"hostid":"",
//									"port":"",
//								};
//							var empObj=[];
//							var aa;
//							for(var i=0;i<resultJson.data.length;i++){
//								if(i%2 == 0){
//									emp.podName1=resultJson.data[i].podName;
//									
//								}else{
//									emp.podName2=resultJson.data[i].podName;
//								}
//								emp[i]={
//									"id":resultJson.data[i].id,
//									"miroservice":resultJson.data[i].miroservice,
//									"namespace":resultJson.data[i].namespace,
//									"containerName":resultJson.data[i].containerName,
//									"podName1":emp.podName1,
//								    "podName2":emp.podName2,
//									"service":resultJson.data[i].service,
//									"hostid":resultJson.data[i].ip,
//									"port":resultJson.data[i].port,
//							   };
//								if(i%2 == 1){
//									//奇数
//									empObj.push(emp[i]);
//								 }
//							}
////							
//							console.log(empObj);
							 controller.miroserviceConfigList =resultJson.data;
							 controller.paginationInfo.totalPages =resultJson.totalPages;
							 controller.paginationInfo.totalElements =resultJson.totalElements;
							 //手动刷新
							 	$scope.$apply();  
							 },errro:function(){
								 console.log("请求错误！")
							 }
							 });

						}
						
						// 获取树状图数据
						function getTreeData(type,data) { //1:选择ip弹窗  2：新增弹窗
							selectedMap=data.ipMap;
							selectedHostidsDb=[];
							selectedNames=[];
							tdInputId=data.id;
							for(var key in selectedMap){
								selectedHostidsDb.push(parseInt(key));
								selectedNames.push(selectedMap[key]);
							}
						
							var basePath = $scope.getAppBasePath();
							var address = "";
							$
									.ajax({
										type : "POST",
										url : basePath + "/data/getIpTreeData",
										dataType : "json",
										contentType : "application/json",
										success : function(data) {
											var resultArrary = JSON.parse(data);

											var setting = {
												// 异步加载POST方法
												async : {
													enable : true,
													contentType : "application/json",
													dataType : "text",
													type : "post",
													url : basePath
															+ "/data/asyncGetIpTreeData",
													autoParam : [ "commentId" ],
													otherParam : [
															"hostId",-1														],
													dataFilter : ajaxDataFilter
												},
												// checkBox 效果
												check : {
													enable : true,
													chkStyle : "checkbox"
												},
												callback : {
													onAsyncSuccess : zTreeOnAsyncSuccess,
													onClick : zTreeOnClick,
													onExpand : zTreeOnExpand,// 点击节点前+号加载
													onCheck : zTreeOnCheck// 点击chckBox框加载
												},
											};

											function zTreeOnAsyncSuccess() {
											}
											// checked box 选中 取消时候，ip值的状态设置
											function zTreeOnCheck(event,
													treeId, treeNode) {
											}
											function zTreeBeforeAsync(treeId,
													treeNode) {
												return (treeNode.isParent == true);
											}
											;
											// 返回数据转成json
											function ajaxDataFilter(treeId,parentNode, responseData) {
												responseData = JSON.parse(responseData);
												// 获取已经被配置的Ip，并且设置checked为true
												
												for (var i = 0; i < responseData.length; i++) {
													for(var key in selectedMap){
														if (parseInt(responseData[i].id) ==parseInt(key)) {
																$scope.controller.selectedIpByDbOldEmp.push(responseData[i]);
																responseData[i].checked = "true";
														}
													}
												}

												return responseData;
											};
											if(type==1){
												var zTreeObj = $.fn.zTree.init(
														$("#selectIP"), setting,
														resultArrary);
												//默认展开根目录
												$("#selectIP_1_switch").click();
												
												//选中已经配置过的ips
												var treeObj = $.fn.zTree.getZTreeObj("selectIP");
												var tempArray=selectedNames;
												tempArray=arrayRemoveRepeat(tempArray);//去重
												for(var i=0;i<tempArray.length;i++){
													var node = treeObj.getNodeByParam("name", tempArray[i], null).tId+"_switch";//根据name属性获取树结构节点 tId
													//拿到节点后点击“+"调用异步加载方法
													$("#"+node).click();
												}
												
											}else{
												var zTreeObj = $.fn.zTree.init($("#warningSelectIP"), setting,resultArrary);
									
											}
			
											$scope.zTreeObjNew = zTreeObj;
							
											function zTreeOnExpand(event,
													treeId, treeNode) {
												var nodes = zTreeObj
														.getSelectedNodes();
												if (nodes.length > 0
														&& treeNode.level != 0
														&& treeNode.level != 1) {
													zTreeObj
															.reAsyncChildNodes(
																	nodes[0],
																	"refresh");
												}
											}
											function zTreeOnClick(event,
													treeId, treeNode) {
											}

											// 过滤ztree显示数据
											var hiddenNodes;
											function filter() {
												// 显示上次搜索后背隐藏的结点
												zTreeObj.showNodes(hiddenNodes);
												var _keywords = $("#keyword")
														.val();
												if (_keywords == null
														|| _keywords == "") {
													zTreeObj
															.showNodes(hiddenNodes);
												} else {
													var nodes = zTreeObj
															.getNodesByParamFuzzy(
																	"name",
																	_keywords,
																	null); // 根据节点数据的属性搜索，获取条件模糊匹配的节点数据
																			// JSON
																			// 对象集合,(keywords)模糊匹配只能针对
																			// String
																			// 类型的数据
													if (nodes.length > 0) {
														zTreeObj.selectNode(nodes[0]); // 会让节点自动滚到到可视区域内
													}

													// 查找不符合条件的叶子节点
													function filterFunc(node) {
														var _keywords = $(
																"#keyword")
																.val();
														if (node.isParent
																|| node.name
																		.indexOf(_keywords) != -1) {
															return false;
														} else {
															return true;
														}
													}
													;

													// 获取不符合条件的叶子结点
													hiddenNodes = zTreeObj
															.getNodesByFilter(filterFunc);

													// 隐藏不符合条件的叶子结点
													zTreeObj
															.hideNodes(hiddenNodes);
												}
											}
											;
										}
									});
						}

						

					})
					
			//新增				
			.controller(
					'insertMicroServiceController',
					function($scope, $uibModalInstance, $http, $log) {
						var basePath = $scope.getAppBasePath();
						var controller = this;
						this.indexList = [];
						this.kpiList = [];
						// INSERT参数定义
						
						// 程序初期化
						this.init = function() {
					
						}
						this.init();
						
						$scope.save = function() {
							console.log($(".podName").length);
							insertComponent = {
									"miroservice" : "",
									"namespace" : "",
									"container_name" : "",
									"service" : "",
									"hostid":"",
									"port":"",
									"podName":""
							};
							
							// INSERT值获取
							insertComponent.miroservice = $scope.$parent.insertComponent.miroservice;
							insertComponent.namespace = $scope.$parent.insertComponent.namespace;
							insertComponent.container_name = $scope.$parent.insertComponent.container_name;
							insertComponent.service = $scope.$parent.insertComponent.service;
							insertComponent.port = $scope.$parent.insertComponent.port;
							insertComponent.podName = $scope.$parent.insertComponent.podName;
							
//							
							//提交验证
							if(insertComponent.miroservice==''||insertComponent.miroservice==null){
								alert("服务名不能为空！");
								return
							}
							if(insertComponent.namespace==''||insertComponent.namespace==null){
								alert("集群空间名不能为空！");
								return
							}
							if(insertComponent.container_name==''||insertComponent.container_name==null){
								alert("容器不能为空！");
								return
							}
							if(insertComponent.service==''||insertComponent.service==null){
								alert("服务单元名不能为空！");
								return
							}
							 if(insertComponent.podName== "" || insertComponent.podName== null){
							alert("端口号不能为空！");
							return
						}
							//获取选中的ip
				            var treeObj=$.fn.zTree.getZTreeObj("warningSelectIP");
				            selectedIp=treeObj.getCheckedNodes(true);
				            hostids=""; 
				            console.log(selectedIp);
							if(selectedIp.length==0){
								alert("请选择主机号后保存！");
								return;
							}
							if(selectedIp.length != 3){
								alert("主机号只能单选！");
								return;
							}
							//获取选中ip节点
							 var emp=[];
						     var empObjList=[];
						    	 for (var i = 0; i < selectedIp.length; i++) {
										if (selectedIp[i].chidren == undefined && selectedIp[i].isParent == false) 
										{
											console.log(selectedIp[i].id);
								                emp[i]={
								                    "miroservice":insertComponent.miroservice,
								                    "namespace":insertComponent.namespace,
								                    "containerName":insertComponent.container_name,
								                    "hostid":selectedIp[i].id,
								                    "service":insertComponent.service,
								                    "port":insertComponent.port,
								                    "podName":insertComponent.podName
								                };
								                empObjList.push(emp[i]);
										}
									}
						   
							
				            
							//insertComponent.hostids = hostids;
							console.log(JSON.stringify(empObjList));
							// 后台调用
							$.ajax({
								type : "POST",
								url :  basePath+ "/data/insertMiroService",
								dataType : "json",
								contentType : 'application/json;charset=utf-8',//指定为json类型 
								data : JSON.stringify(empObjList),
								success : function(data) {
									$uibModalInstance.close();
									alert("插入成功");
								}
							});
							
						};
						$scope.cancel = function() {
							// dismiss也是在模态框关闭的时候进行调用,而它返回的是一个reason
							$uibModalInstance.dismiss('cancel');
						};
					})
					//编辑配置
					.controller(
							'updateMicroServiceController',
							function($scope, $uibModalInstance, $http, $log) {
								var basePath = $scope.getAppBasePath();
								var controller = this;
								this.indexList = [];
								this.kpiList = [];
								$scope.times="";
								$scope.minutes="";
								
								// 程序初期化
								this.init = function() {
								}
								this.init();
								
								$scope.updatesave = function() {
									
									 if($scope.miroservice== "" || $scope.miroservice== undefined){
											alert("微服务名不能为空！");
											return
										}
			                            if($scope.namespace== "" || $scope.namespace== undefined){
											alert("集群空间名不能为空！");
											return
										}
			                            if($scope.containerName== "" || $scope.containerName== undefined){
											alert("容器名不能为空！");
											return
										}
			                            if($scope.service== "" || $scope.service== undefined){
											alert("服务单元名不能为空！");
											return
										}
			                            if($scope.podName== "" || $scope.podName== undefined){
											alert("端口号不能为空！");
											return
										}
									// INSERT值获取
	                           
	                                var emp=[];
	                                var upempObj=[];
	                                for(var i=0;i<1;i++){
	                                	 emp[i]={
		 	                    					"miroservice":$scope.miroservice,
		 	                    					"namespace":$scope.namespace,
		 	                    					"containerName":$scope.containerName,
		 	                    					"service":$scope.service,
		 	                    					"id":$scope.id,
		 	                    					"hostid":$scope.hostid,
		 	                    					"port":$scope.port,
		 	                    					"podName":$scope.podName
		 	                    		 };
	                                	 upempObj.push(emp[i]);
	                                }
	                                	
	                               
	                               
									// 后台调用
									$.ajax({
										type : "POST",
										url :  basePath+ "/data/updateMiroService",
										dataType : "json",
										contentType : 'application/json;charset=utf-8',//指定为json类型 
										data :JSON.stringify(upempObj),
										success : function(data) {
											console.log(data);
											alert("编辑成功！");
											$uibModalInstance.close();
											
										}
									});
									
								};
								$scope.cancel = function() {
									// dismiss也是在模态框关闭的时候进行调用,而它返回的是一个reason
									$uibModalInstance.dismiss('cancel');
								};
							})
					
			
})();